<template>
	<div>
		<jk-dialog
			v-model="showDialog"
			:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-机台分段`"
			width="1260px"
			:show-content-loading="showLoading"
			:confirm-btn-loading="confirmBtnLoading"
			:show-confirm-btn="pageType !== 'detail'"
			:show-cancel-btn="pageType !== 'detail'"
			:show-close-btn="pageType === 'detail'"
			@on-close="onVisibleChange(false)"
			@on-cancel="onVisibleChange(false)"
			@on-visible-change="onVisibleChange"
			@on-confirm="onConfirmBtn"
		>
			<el-form ref="ruleForm" :model="fromData" :rules="rules" :hide-required-asterisk="pageType === 'detail'" label-width="120px" :show-message="false">
				<div ref="box1">
					<el-tag type="primary" effect="plain" class="margin-bottom-4">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<jk-card>
						<el-row class="flex-start-center-wrap">
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="机台">
									<span class="read-only-2">{{ ruleForm.machineName }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="车间">
									<span class="read-only-2">{{ ruleForm.workshopName }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-0" label="工序">
									<span class="read-only-2">{{ ruleForm.processName }}</span>
								</el-form-item>
							</el-col>
							<!--<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="日期">
									<span class="read-only-2">{{ ruleForm.belongDate }}</span>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item class="margin-bottom-10" label="班次">
									<span class="read-only-2">{{ ruleForm.scheduleShiftId }}</span>
								</el-form-item>
							</el-col>-->
						</el-row>
					</jk-card>
				</div>
				<div ref="box2" class="margin-bottom-4 margin-top-10 flex-between-center">
					<div class="flex-start-center" style="font-size: 13px;align-items: flex-end;display: flex;align-items: center">
						<el-tag type="primary" effect="plain" class="" @click="onAddBtn">
							<span class="el-icon-tickets item-gap"></span>
							<span>分段列表</span>
						</el-tag>
						<div class="margin-left-10">
							班次时间: {{ ruleForm.machineProductRecordsList[0] && ruleForm.machineProductRecordsList[0].schShiftStartDateTime }} - {{ ruleForm.machineProductRecordsList[0] &&ruleForm.machineProductRecordsList[0].schShiftEndDateTime }}
						</div>
					</div>
					<div>

					</div>
				</div>
				<jk-table
					ref="jkTable"
					border
					:data="ruleForm.machineProductRecordsList || []"
					:height="dialogTableHeight - 20"
				>
					<vxe-column title="序号" align="center" type="seq" :width="60"></vxe-column>
					<vxe-column title="开始时间" align="left" field="startDateTime" :width="200">
						<template slot-scope="scope">
							<!--:picker-options="pickerOptions"-->
							<jk-date-picker
								v-model="scope.row.startDateTime"
								type="datetime"
								:clearable="false"
								size="mini"
								@change="onStartTime($event,scope.rowIndex, scope.row)"
							></jk-date-picker>
						</template>
					</vxe-column>
					<vxe-column title="结束时间" align="left" field="endDateTime" :width="200">
						<template slot-scope="scope">
							<!--:picker-options="pickerOptions"-->
							<jk-date-picker
								v-model="scope.row.endDateTime"
								type="datetime"
								:clearable="false"
								size="mini"
								@change="onEndTime($event, scope.rowIndex, scope.row)"
							></jk-date-picker>
						</template>
					</vxe-column>

					<vxe-column title="采集品种" align="left" field="machineProductName" :width="150"></vxe-column>
					<vxe-column title="计划品种" align="left" field="productName" :min-width="180">
						<template slot-scope="scope">
							<jk-button class="width-100-percent" size="mini" @click="onEditProductBtn(scope.rowIndex)">
								<span class="item-gap">{{ scope.row.productName || '选择' }}</span>
								<span class="el-icon-edit-outline"></span>
							</jk-button>
						</template>
					</vxe-column>
					<!--<vxe-column title="批号" align="left" field="batchCode" :width="120"></vxe-column>-->
					<vxe-column
						:visible="ruleForm.processCode && ruleForm.processCode !== 'LT'"
						title="开始产量表数(M)"
						align="left"
						field="startOutputM"
						:width="120"
					>
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.startOutputM" size="mini" icon="el-icon-minus"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column
						:visible="ruleForm.processCode && ruleForm.processCode !== 'LT'"
						title="结束产量表数(M)"
						align="left"
						field="endOutputM"
						:width="120"
					>
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.endOutputM" size="mini" icon="el-icon-minus"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column
						:visible="ruleForm.processCode && ruleForm.processCode !== 'LT'"
						title="产量(M)"
						align="left"
						field="outputM"
						:width="100"
					>
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.outputM" size="mini" icon="el-icon-minus"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column
						:visible="ruleForm.processCode && ruleForm.processCode === 'LT'"
						title="开始产量表数(kg)"
						align="left"
						field="startOutputKg"
						:width="120"
					>
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.startOutputKg" size="mini" icon="el-icon-minus"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column
						:visible="ruleForm.processCode && ruleForm.processCode === 'LT'"
						title="结束产量表数(kg)"
						align="left"
						field="endOutputKg"
						:width="120"
					>
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.endOutputKg" size="mini" icon="el-icon-minus"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column
						:visible="ruleForm.processCode && ruleForm.processCode === 'LT'"
						title="产量(kg)"
						align="left"
						field="outputKg"
						:width="100"
					>
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.outputKg" size="mini" icon="el-icon-minus"></jk-number-input>
						</template>
					</vxe-column>
				</jk-table>
			</el-form>
		</jk-dialog>
		<select-machine-task-dialog
			:form-data="ruleForm"
			:dialog-state="selectMachineTaskDialogState"
			@on-visible-change="onVisibleChangeOfSelectMachineTaskDialog"
			@on-confirm="onConfirmBtnOfSelectMachineTaskDialog"
		></select-machine-task-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import selectMachineTaskDialog from './components/select-machine-task-dialog2';
    import {
        productionMachineProductRecordsBatchUpdate
    } from '@/api/production/machineProductRecords';
    import { productionPrdNoticeMachineChangeGetMachineData } from '../../../api/production/xsOpen';
    import { mathJsSub } from '../../../utils/jk/jk-cals';
    export default {
        components: {
            selectMachineTaskDialog
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            pageType: {
                type: String,
                default: ''
            },
            fromData: {
                type: Object,
                default: () => {}
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                selectMachineTaskDialogState: false,
                processList: [],
                showDialog: false,
                showLoading: false,
                confirmBtnLoading: false,
                updataEndDateTime: '',
                ruleForm: {
                    id: null,
                    machineId: null,
                    machineName: '',
                    processCode: '',
                    remark: '',
                    machineProductRecordsList: []
                },
                rules: {}
            };
        },
        computed: {
            pickerOptions() {
                const startTime = new Date(this.ruleForm.machineProductRecordsList[0].schShiftStartDateTime);
                const endTime = new Date(this.ruleForm.machineProductRecordsList[0].schShiftEndDateTime);

                return {
                    disabledDate(time) {
                        return time.getTime() < startTime.getTime() || time.getTime() > endTime.getTime();
                    }
                };
            }
        },
        methods: {
            onAddBtn() {
                this.ruleForm.machineProductRecordsList.push({
                    startDateTime: '',
                    endDateTime: '',
                    machineProductName: '',
                    productId: '',
                    productName: '',
                    startOutputM: '',
                    endOutputKg: '',
                    outputM: '',
                    outputKg: ''
                });
            },
            onEditProductBtn(rowIndex) {
                this.editRowIndex = rowIndex;
                this.selectMachineTaskDialogState = true;
            },
            // 调整时间记录的函数
            adjustTimeRecords(changedIndex, newStartTime) {
                const records = this.ruleForm.machineProductRecordsList;

                // 更新当前记录的结束时间为新的开始时间
                for (let i = changedIndex; i < records.length; i++) {
                    const record = records[i];

                    // 更新当前记录的结束时间
                    if (newStartTime > record.endDateTime) {
                        record.endDateTime = newStartTime;
                        this.updataEndDateTime = record.endDateTime;
                    }

                    // 确保下一个记录的开始时间不能早于当前记录的结束时间=>(和下面是重复逻辑可以去掉)
                    // if (i < records.length - 1) {
                    //     const nextRecord = records[i + 1];
                    //     if (nextRecord.startDateTime < record.endDateTime) {
                    //         nextRecord.startDateTime = record.endDateTime;
                    //     }
                    // }
                }
                // 更新结束时间为下一个记录的开始时间，并同步 startOutputM
                for (let i = changedIndex; i < records.length - 1; i++) {
                    const currentRecord = records[i];
                    const nextRecord = records[i + 1];

                    // 更新下一个记录的开始时间
                    nextRecord.startDateTime = currentRecord.endDateTime;

                    // 如果下一个记录的开始时间与当前记录的结束时间相同，则同步 startOutputM
                    if (nextRecord.startDateTime === currentRecord.endDateTime) {
                        setTimeout(() => { // 简单粗暴
                            nextRecord.startOutputM = records[0].endOutputM;
                        }, 200);
                    }
                }
            },
            // 如果上一次endDateTime的时间和下一个startDateTime的时间相同,那startOutputM的值就和上一个endOutputM值一样
            // 公共的时间验证和更新方法
            validateAndUpdateTime(newTime, row, type, rowIndex) {
                const { startDateTime, endDateTime } = this.ruleForm.machineProductRecordsList[rowIndex];
                const originalTime = type === 'start' ? startDateTime : endDateTime;
                const isValid = (newTime >= row.schShiftStartDateTime) && (newTime <= row.schShiftEndDateTime);

                const records = this.ruleForm.machineProductRecordsList;

                // 仅对第二条数据（rowIndex为1）的开始时间进行限制
                if (rowIndex > 1 && type === 'start') {
                    const isInPreviousRange = records.slice(0, rowIndex).some(record => {
                        return newTime >= record.startDateTime && newTime <= record.endDateTime;
                    });

                    if (isInPreviousRange) {
                        this.$tipsBar(this, 'custom', 'warning', '选择的时间不能在之前记录的时间范围内。');
                        this.$nextTick(() => {
                            this.$set(row, 'startDateTime', originalTime);
                        });
                        return false;
                    }
                }

                if (!isValid) {
                    this.$tipsBar(this, 'custom', 'warning', `请选择排班的时间范围内:${row.schShiftStartDateTime}-${row.schShiftEndDateTime}`);
                    this.$nextTick(() => {
                        this.$set(row, type === 'start' ? 'startDateTime' : 'endDateTime', originalTime);
                    });
                    return false;
                }

                if (type === 'end' && newTime < row.startDateTime) {
                    this.$tipsBar(this, 'custom', 'warning', `选择时间需要大于开始时间`);
                    this.$nextTick(() => {
                        this.$set(row, 'endDateTime', this.updataEndDateTime || originalTime);
                    });
                    return false;
                }

                return true;
            },
            onStartTime(newStartTime, rowIndex, row) {
                if (this.validateAndUpdateTime(newStartTime, row, 'start', rowIndex)) {
                    this.$set(this.ruleForm.machineProductRecordsList[rowIndex], 'startDateTime', newStartTime);
                    this.getGatherMachineDataRequest('start', rowIndex, newStartTime);
                    this.adjustTimeRecords(rowIndex, newStartTime);
                }
            },

            onEndTime(newEndTime, rowIndex, row) {
                if (this.validateAndUpdateTime(newEndTime, row, 'end', rowIndex)) {
                    this.$set(this.ruleForm.machineProductRecordsList[rowIndex], 'endDateTime', newEndTime);
                    this.getGatherMachineDataRequest('end', rowIndex, newEndTime);
                    this.adjustTimeRecords(rowIndex, newEndTime);
                }
            },

            // 获取指定机台采集的仪表数据
            getGatherMachineDataRequest(form, rowIndex, time) {
                if (this.ruleForm.machineId && this.ruleForm.machineCode) {
                    return productionPrdNoticeMachineChangeGetMachineData({
                        machineId: this.ruleForm.machineId,
                        machineCode: this.ruleForm.machineCode,
                        selectDateTime: time
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.setGatherData(form, rowIndex, res.data.res || {});
                        }
                    });
                }
            },
            setGatherData(form, rowIndex, data) {
                const record = this.ruleForm.machineProductRecordsList[rowIndex];
                const updateFields = (fields) => {
                    fields.forEach(([key, value]) => {
                        record[key] = value;
                    });
                };
                if (form === 'start') {
                    updateFields([
                        ['startElectricEnergy', data.currentElectricEnergy || 0],
                        ['startSystemElectricEnergy', data.currentElectricEnergy || 0],
                        ['startOutputM', data.currentOutput || 0],
                        ['startSystemOutput', data.currentOutput || 0],
                        ['lastEndOutput', data.lastEndOutput || 0],
                        ['lastEndElectricEnergy', data.lastEndElectricEnergy || 0],
                        ['openSpinCount', (data.spinCount - data.usedSpinCount) || 0],
                        ['usedSpinCount', data.usedSpinCount || 0],
                        ['spinCount', data.spinCount || 0],
                        ['startOutputKg', data.currentOutputKg || 0],
                        ['startSystemOutputKg', data.currentOutputKg || 0]
                    ]);
                } else {
                    updateFields([
                        ['reportElectricEnergy', data.reportElectricEnergy || 0],
                        ['reportOutput', data.reportOutput || 0],
                        ['reportQty', data.reportQty || 0],
                        ['endElectricEnergy', data.currentElectricEnergy || 0],
                        ['endSystemElectricEnergy', data.currentElectricEnergy || 0],
                        ['endOutputM', data.currentOutput || 0],
                        ['endSystemOutput', data.currentOutput || 0],
                        ['endOutputKg', data.currentOutputKg || 0],
                        ['endSystemOutputKg', data.currentOutputKg || 0]
                    ]);
                }
                // 计算产量差值
                record.outputM = mathJsSub(record.endOutputM || 0, record.startOutputM || 0);
                record.outputKg = mathJsSub(record.endOutputKg || 0, record.startOutputKg || 0);
            },
            updateFields(rowIndex, fields, data) {
                fields.forEach(field => {
                    this.$set(this.ruleForm.machineProductRecordsList[rowIndex], field, data[field]);
                });
            },

            onConfirmBtnOfSelectMachineTaskDialog(e) {
                const fieldsToUpdate = ['prdNoticeMachineChangeId', 'productId', 'productCode', 'productName', 'batchCode'];
                // 更新选中行
                e.prdNoticeMachineChangeId = e.id;
                this.updateFields(this.editRowIndex, fieldsToUpdate, e);
                /* // 更新选中行以下的所有行
                for (let i = this.editRowIndex + 1; i < this.ruleForm.machineProductRecordsList.length; i++) {
                    this.updateFields(i, fieldsToUpdate, e);
                }*/
                this.selectMachineTaskDialogState = false;
            },
            onVisibleChangeOfSelectMachineTaskDialog(e) {
                this.selectMachineTaskDialogState = e;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.confirmBtnLoading = true;
                        productionMachineProductRecordsBatchUpdate(this.getParamData()).then(res => {
                            this.confirmBtnLoading = false;
                            if (res.data.status === 200) {
                                this.$tipsBar(this, 'save');
                                this.$emit('on-finish');
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.ruleForm = this.fromData ? JSON.parse(JSON.stringify(this.fromData)) : {};
                    // 修复动态显示表头错乱的问题
                    this.$nextTick(() => {
                        this.$refs.jkTable.$refs.xTable.refreshColumn();
                    });
                }
            }
        }
    };
</script>
